/**
 * 支付宝支付服务类 - 浏览器方案
 * 优先使用浏览器跳转，提供更稳定的支付体验
 */

//import { plus, uni } from "some-module" // Declare plus and uni variables

export class AlipayService {
  constructor() {
    this.platform = this.getPlatform()
  }

  // 获取当前平台
  getPlatform() {
    // #ifdef APP-PLUS
    return "app"
    // #endif

    // #ifdef H5
    return "h5"
    // #endif

    // #ifdef MP-WEIXIN
    return "mp-weixin"
    // #endif

    return "unknown"
  }

  // 检查是否安装了支付宝 - 简化版本
  async checkAlipayInstalled() {
    return new Promise((resolve) => {
      // #ifdef APP-PLUS
      try {
        if (!plus || !plus.runtime) {
          resolve(false)
          return
        }

        // 检查支付宝是否安装（用于显示提示信息）
        const packages = ["com.eg.android.AlipayGphone.sandbox", "com.eg.android.AlipayGphone"]

        for (const packageName of packages) {
          try {
            if (plus.runtime.isApplicationExist({ pname: packageName })) {
              console.log("检测到支付宝:", packageName)
              resolve(true)
              return
            }
          } catch (e) {
            continue
          }
        }

        resolve(false)
      } catch (error) {
        console.error("检查支付宝安装状态失败:", error)
        resolve(false)
      }
      // #endif

      // #ifndef APP-PLUS
      resolve(false)
      // #endif
    })
  }

  // 主要支付方法 - 浏览器优先方案
  async pay(orderString) {
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      // App环境优先使用浏览器方案
      this.payWithBrowser(orderString, resolve, reject)
      // #endif

      // #ifdef H5
      // H5环境直接使用浏览器
      this.payInH5(orderString)
      resolve({ resultStatus: "9000", result: "success" })
      // #endif

      // #ifdef MP-WEIXIN
      // 小程序环境
      this.payInMiniProgram(orderString)
      resolve({ resultStatus: "9000", result: "success" })
      // #endif
    })
  }

  // App环境浏览器支付 - 新方案
  async payWithBrowser(orderString, resolve, reject) {
    try {
      // 创建支付页面HTML
      const paymentHtml = this.createPaymentHtml(orderString, "支付宝支付")

      // 获取可用的浏览器列表
      const browsers = this.getAvailableBrowsers()

      // 显示浏览器选择对话框
      this.showBrowserSelection(browsers, paymentHtml, resolve, reject)
    } catch (error) {
      console.error("浏览器支付失败:", error)
      reject(error)
    }
  }

  // 获取可用浏览器列表
  getAvailableBrowsers() {
    const browsers = [
      {
        name: "百度浏览器",
        package: "com.baidu.browser.apps",
        action: "android.intent.action.VIEW",
      },
      {
        name: "Chrome浏览器",
        package: "com.android.chrome",
        action: "android.intent.action.VIEW",
      },
      {
        name: "系统浏览器",
        package: "com.android.browser",
        action: "android.intent.action.VIEW",
      },
      {
        name: "UC浏览器",
        package: "com.UCMobile",
        action: "android.intent.action.VIEW",
      },
      {
        name: "QQ浏览器",
        package: "com.tencent.mtt",
        action: "android.intent.action.VIEW",
      },
    ]

    // #ifdef APP-PLUS
    if (plus && plus.runtime) {
      return browsers.filter((browser) => {
        try {
          return plus.runtime.isApplicationExist({ pname: browser.package })
        } catch (e) {
          return false
        }
      })
    }
    // #endif

    return browsers
  }

  // 显示浏览器选择对话框
  showBrowserSelection(browsers, paymentHtml, resolve, reject) {
    if (browsers.length === 0) {
      // 没有可用浏览器，使用WebView
      this.payWithWebView(paymentHtml, {}, resolve, reject)
      return
    }

    // 优先使用百度浏览器
    const baiduBrowser = browsers.find((b) => b.package === "com.baidu.browser.apps")
    const defaultBrowser = baiduBrowser || browsers[0]

    uni.showModal({
      title: "选择浏览器支付",
      content: `将使用${defaultBrowser.name}打开支付页面，支付完成后请手动返回应用`,
      cancelText: "取消支付",
      confirmText: "确认支付",
      success: (res) => {
        if (res.confirm) {
          this.openBrowserPayment(defaultBrowser, paymentHtml, resolve, reject)
        } else {
          reject(new Error("用户取消支付"))
        }
      },
      fail: () => {
        reject(new Error("无法显示支付确认"))
      },
    })
  }

  // 使用指定浏览器打开支付页面
  async openBrowserPayment(browser, paymentHtml, resolve, reject) {
    try {
      // #ifdef APP-PLUS
      // 创建临时HTML文件
      const tempFilePath = await this.createTempHtmlFile(paymentHtml)

      // 使用指定浏览器打开
      const Intent = plus.android.importClass("android.content.Intent")
      const Uri = plus.android.importClass("android.net.Uri")
      const ComponentName = plus.android.importClass("android.content.ComponentName")
      const main = plus.android.runtimeMainActivity()

      const intent = new Intent()
      intent.setAction(browser.action)
      intent.setData(Uri.parse(`file://${tempFilePath}`))

      // 指定浏览器包名
      if (browser.package !== "com.android.browser") {
        intent.setPackage(browser.package)
      }

      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

      main.startActivity(intent)

      console.log(`成功使用${browser.name}打开支付页面`)

      // 监听应用返回前台
      this.addResumeListener(resolve, reject)
      // #endif
    } catch (error) {
      console.error(`使用${browser.name}打开支付失败:`, error)

      // 降级到WebView
      this.payWithWebView(paymentHtml, {}, resolve, reject)
    }
  }

  // 创建临时HTML文件
  createTempHtmlFile(htmlContent) {
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      try {
        const fs = plus.io.requestFileSystem(
          plus.io.PRIVATE_WWW,
          (fs) => {
            const fileName = `payment_${Date.now()}.html`
            fs.root.getFile(
              fileName,
              { create: true },
              (fileEntry) => {
                fileEntry.createWriter((writer) => {
                  writer.onwrite = () => {
                    resolve(fileEntry.fullPath)
                  }
                  writer.onerror = reject
                  writer.write(htmlContent)
                })
              },
              reject,
            )
          },
          reject,
        )
      } catch (error) {
        reject(error)
      }
      // #endif

      // #ifndef APP-PLUS
      reject(new Error("非App环境不支持文件创建"))
      // #endif
    })
  }

  // 创建支付页面HTML - 优化版本
  createPaymentHtml(formData, title) {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <title>${title}</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
          }
          .container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 500px;
            width: 100%;
          }
          .logo {
            width: 80px;
            height: 80px;
            background: #1677ff;
            border-radius: 50%;
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            font-weight: bold;
          }
          .title {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
          }
          .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 16px;
          }
          .btn {
            width: 100%;
            height: 50px;
            background: #1677ff;
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 15px;
          }
          .btn:hover {
            background: #0958d9;
            transform: translateY(-2px);
          }
          .btn:active {
            transform: translateY(0);
          }
          .form-container {
            display: none;
          }
          .loading {
            display: none;
            margin: 20px 0;
          }
          .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #1677ff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          .tips {
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-radius: 10px;
            padding: 15px;
            margin: 20px 0;
            color: #0369a1;
            font-size: 14px;
            line-height: 1.5;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="logo">支</div>
          <h2 class="title">支付宝支付</h2>
          <p class="subtitle">安全便捷的支付体验</p>
          
          <div class="tips">
            💡 支付完成后，请手动返回应用查看订单状态
          </div>
          
          <div id="payment-content">
            <button class="btn" onclick="startPayment()">立即支付</button>
          </div>
          
          <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在跳转到支付宝...</p>
          </div>
          
          <div class="form-container">
            ${formData}
          </div>
        </div>
        
        <script>
          function startPayment() {
            document.getElementById('payment-content').style.display = 'none';
            document.getElementById('loading').style.display = 'block';
            
            setTimeout(() => {
              const form = document.querySelector('form');
              if (form) {
                form.submit();
              } else {
                alert('支付数据异常，请重试');
                resetPayment();
              }
            }, 1000);
          }
          
          function resetPayment() {
            document.getElementById('payment-content').style.display = 'block';
            document.getElementById('loading').style.display = 'none';
          }
          
          // 自动开始支付
          window.onload = function() {
            console.log('支付页面加载完成');
            // 延迟自动开始支付
            setTimeout(startPayment, 1000);
          };
        </script>
      </body>
      </html>
    `
  }

  // 添加应用返回前台监听器
  addResumeListener(resolve, reject) {
    let resumed = false

    const handleResume = () => {
      if (resumed) return
      resumed = true

      // 移除事件监听器
      try {
        if (document && document.removeEventListener) {
          document.removeEventListener("resume", handleResume)
        }
      } catch (e) {
        console.log("移除事件监听器失败:", e)
      }

      // 显示支付确认对话框
      setTimeout(() => {
        this.showPaymentConfirmation(resolve, reject)
      }, 500)
    }

    // 添加事件监听器
    try {
      if (document && document.addEventListener) {
        document.addEventListener("resume", handleResume, { once: true })
        console.log("成功添加resume监听器")
      }
    } catch (error) {
      console.error("添加resume监听器失败:", error)
    }

    // 设置超时处理
    setTimeout(() => {
      if (!resumed) {
        resumed = true
        this.showPaymentConfirmation(resolve, reject)
      }
    }, 300000) // 5分钟超时
  }

  // 显示支付确认对话框
  showPaymentConfirmation(resolve, reject) {
    uni.showModal({
      title: "支付确认",
      content: "请确认您的支付状态",
      cancelText: "支付失败",
      confirmText: "支付成功",
      success: (res) => {
        if (res.confirm) {
          resolve({
            resultStatus: "9000",
            result: "success",
            memo: "支付成功",
          })
        } else {
          resolve({
            resultStatus: "6001",
            result: "cancel",
            memo: "用户取消支付",
          })
        }
      },
      fail: () => {
        resolve({
          resultStatus: "6001",
          result: "cancel",
          memo: "无法确认支付状态",
        })
      },
    })
  }

  // WebView支付 - 降级方案
  async payWithWebView(formData, options = {}, resolve, reject) {
    // #ifdef APP-PLUS
    try {
      if (!plus || !plus.webview) {
        reject(new Error("WebView环境不可用"))
        return
      }

      const webview = plus.webview.create("", "alipay-payment", {
        top: "0px",
        bottom: "100px",
        background: "#ffffff",
      })

      webview.loadData(formData)
      webview.show()

      // 添加工具栏
      this.addWebViewToolbar(webview, resolve, reject)

      webview.addEventListener("loaded", () => {
        console.log("WebView支付页面加载完成")
      })

      webview.addEventListener("error", (error) => {
        console.error("WebView支付页面加载失败:", error)
        reject(error)
      })
    } catch (error) {
      console.error("创建WebView失败:", error)
      reject(error)
    }
    // #endif
  }

  // 添加WebView工具栏
  addWebViewToolbar(webview, resolve, reject) {
    // #ifdef APP-PLUS
    try {
      const toolbar = plus.nativeObj.createView("toolbar", {
        top: plus.screen.resolutionHeight - 100 + "px",
        left: "0px",
        width: "100%",
        height: "100px",
        backgroundColor: "#ffffff",
      })

      toolbar.drawRect(
        {
          color: "#e5e5e5",
          radius: "0px",
        },
        {
          top: "0px",
          left: "0px",
          width: "100%",
          height: "1px",
        },
      )

      toolbar.drawText(
        "关闭支付",
        {
          top: "20px",
          left: "20px",
          width: "100px",
          height: "60px",
        },
        {
          size: "16px",
          color: "#666666",
          align: "center",
        },
      )

      toolbar.drawText(
        "检查支付状态",
        {
          top: "20px",
          right: "20px",
          width: "120px",
          height: "60px",
        },
        {
          size: "16px",
          color: "#1677ff",
          align: "center",
        },
      )

      toolbar.addEventListener("click", (event) => {
        if (event.clientX < 140) {
          webview.close()
          toolbar.close()
          reject(new Error("用户取消支付"))
        } else if (event.clientX > plus.screen.resolutionWidth - 140) {
          this.showPaymentConfirmation(resolve, reject)
        }
      })

      toolbar.show()

      webview.addEventListener("close", () => {
        toolbar.close()
      })
    } catch (error) {
      console.error("创建工具栏失败:", error)
    }
    // #endif
  }

  // H5环境支付
  payInH5(formData) {
    const payWindow = window.open("", "_blank", "width=800,height=600,scrollbars=yes,resizable=yes")

    if (payWindow) {
      const html = this.createPaymentHtml(formData, "支付宝支付")
      payWindow.document.write(html)
      payWindow.document.close()
    } else {
      throw new Error("无法打开支付窗口，请检查浏览器设置")
    }
  }

  // 小程序环境处理
  payInMiniProgram(formData) {
    uni.setClipboardData({
      data: formData,
      success: () => {
        uni.showModal({
          title: "支付提示",
          content: "支付链接已复制，请在浏览器中打开完成支付",
          showCancel: false,
          confirmText: "知道了",
        })
      },
    })
  }
}

// 导出单例
export const alipayService = new AlipayService()
